package com.kye.express.business.invoice_online;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.invoice_online.history.InvoiceHistoryActivity;
import com.kye.express.business.scanner.ScannerActivity;
import com.kye.express.databinding.ActivityInvoiceOnlineBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.invoice_online.GeneratedInvoiceDataResultBean;
import com.kye.model.bean.invoice_online.GetInvoicedListResultBean;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 在线开票
 */
public class InvoiceOnlineActivity extends BaseToolbarActivity implements InvoiceOnlineActivityContract.InvoiceOnlineActivityView, InvoiceOnlineItemViewBinder.OnCheckedListener {
    private static final int REQUEST_CODE_SCANNER = 1;
    private ActivityInvoiceOnlineBinding mBinding;
    private Context mContext;
    private InvoiceOnlineActivityContract.InvoiceOnlineActivityViewPresenter mPresenter;

    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();
    private Dialog mLoadingDialog;
    private ArrayList<GeneratedInvoiceDataResultBean> mGeneratedInvoiceDatas = new ArrayList<>();

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, InvoiceOnlineActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_invoice_online);
        mContext = this;
        mPresenter = new InvoiceOnlineActivityContract.InvoiceOnlineActivityViewPresenter(this);
        mPresenter.bind(this);
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        setTitle(getString(R.string.invoice_online));
        initView();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    private void initView() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(GetInvoicedListResultBean.class, new InvoiceOnlineItemViewBinder(mContext, this));
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        RecyclerViewDivider.with(mContext)
                .color(getResources().getColor(R.color.grey))
                .size(ScreenUtils.dp2px(mContext, 1))
                .hideLastDivider()
                .build()
                .addTo(mBinding.recyclerview);
        mBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        mBinding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.getInvoicedListData(false, false);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPresenter.getInvoicedListData(false, true);
            }

        });
        mPresenter.getInvoicedListData(true, false);
    }

    private void initEvent() {
        RxView.clicks(mBinding.ibAdd)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String waybillNo = mBinding.edtWaybill.getText().toString().trim();
                        if (!TextUtils.isEmpty(waybillNo)) {
                            mPresenter.findWaybillAmount(waybillNo);
                        } else {
                            ToastManager.show(mContext, R.string.invoice_online_waybill_is_null, Toast.LENGTH_SHORT);
                        }
                    }
                });
        RxView.clicks(mBinding.ivScan)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        startActivityForResult(new Intent(mContext, ScannerActivity.class), REQUEST_CODE_SCANNER);
                    }
                });
        RxView.clicks(mBinding.tvGenerate)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        double totalPrice = getTotalPrice();
                        if (totalPrice > 0) {
                            mPresenter.generatedData(getSelectedWaybillList());
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCANNER && data != null) {
            String waybill = data.getStringExtra(ScannerActivity.KEY_SCANNER_RESULT);
            if (!TextUtils.isEmpty(waybill)) {
                mBinding.edtWaybill.setText(waybill);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_invoice_online, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_record:
                InvoiceHistoryActivity.startActivity(mContext);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onComplete(boolean isLoadMore) {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        if (isLoadMore) {
            mBinding.refreshLayout.finishLoadmore();
        } else {
            mBinding.refreshLayout.finishRefresh();
        }
    }

    @Override
    public void onLoading() {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new KyeProgressDialog.Builder(mContext)
                        .build();
            }
            mLoadingDialog.show();
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoaded(List<GetInvoicedListResultBean> resultDatas, boolean isLoadMore) {
        if (resultDatas != null) {
            if (!isLoadMore) {
                mDatas.clear();
                mDatas.addAll(resultDatas);
                mAdapter.notifyDataSetChanged();
            } else {
                List<GetInvoicedListResultBean> datas = (List<GetInvoicedListResultBean>) mAdapter.getItems();
                if (datas != null) {
                    int start = datas.size();
                    datas.addAll(resultDatas);
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
        onDataChanged();
    }

    @Override
    public void onError(String msg, boolean isLoadMore) {
        ToastManager.show(mContext, msg, Toast.LENGTH_SHORT);
        if (isLoadMore) {
            mBinding.refreshLayout.finishLoadmore(false);
        } else {
            mBinding.refreshLayout.finishRefresh(false);
        }
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        onDataChanged();
    }

    @Override
    public void onOtherError(String msg) {
        ToastManager.show(mContext, msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    private void onDataChanged() {
        if (mAdapter.getItems().size() <= 0) {
            mBinding.tvTips.setVisibility(View.VISIBLE);
            mBinding.cardview.setVisibility(View.GONE);
        } else {
            mBinding.tvTips.setVisibility(View.GONE);
            mBinding.cardview.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onCheckStatusChanged() {
        double totalPrice = getTotalPrice();
        mBinding.tvTotalPrice.setText("￥" + totalPrice);
        if (totalPrice > 0) {
            mBinding.rlPrice.setBackgroundResource(R.drawable.common_shape_bg_green);
        } else {
            mBinding.rlPrice.setBackgroundResource(R.drawable.common_shape_bg_gray);
        }
    }

    private double getTotalPrice() {
        double totalPrice = 0;
        List<GetInvoicedListResultBean> datas = (List<GetInvoicedListResultBean>) mAdapter.getItems();
        if (datas != null) {
            for (GetInvoicedListResultBean item : datas) {
                if (item.isChecked()) {
                    totalPrice += item.getMoney();
                }
            }
        }
        return totalPrice;
    }

    private List<GetInvoicedListResultBean> getSelectedWaybillList() {
        List<GetInvoicedListResultBean> selectList = new ArrayList<>();
        List<GetInvoicedListResultBean> datas = (List<GetInvoicedListResultBean>) mAdapter.getItems();
        if (datas != null) {
            for (GetInvoicedListResultBean item : datas) {
                if (item.isChecked()) {
                    selectList.add(item);
                }
            }
        }
        return selectList;
    }


    @Override
    public void onCompleteFindWaybillAmount() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoadedFindWaybillAmount(List<GetInvoicedListResultBean> data) {
        Logger.d("waybill====" + data.get(0).getWaybill());
        if (data != null && data.get(0) != null && (!TextUtils.isEmpty(data.get(0).getWaybill()))) {
            boolean exist = false;
            List<GetInvoicedListResultBean> datas = (List<GetInvoicedListResultBean>) mAdapter.getItems();
            if (datas != null) {
                for (GetInvoicedListResultBean item : datas) {
                    if (data.get(0).getWaybill().equals(item.getWaybill())) {
                        exist = true;
                        break;
                    }
                }
            }

            if (exist) {
                ToastManager.show(mContext, R.string.invoice_online_waybill_exist, Toast.LENGTH_SHORT);
            } else {
                mDatas.add(0, data);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onErrorFindWaybillAmount(String msg) {
        ToastManager.show(mContext, msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoadedGeneratedData(List<GeneratedInvoiceDataResultBean> datas) {
        if (datas != null) {
            mGeneratedInvoiceDatas.clear();
            mGeneratedInvoiceDatas.addAll(datas);
            InvoiceInfoActivity.startActivity(mContext, mGeneratedInvoiceDatas, getTotalPrice());
        }
    }

    @Override
    public void onErrorGeneratedData(String msg) {
        ToastManager.show(mContext, msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }
}
